//
//  LBAVBaseView.m
//  AFNetworking
//
//  Created by 刘文扬 on 2018/3/14.
//

#import "LBAVBaseView.h"
#import <Masonry.h>
#import "ILiveRenderView+LBHelper.h"
#import <MediaPlayer/MediaPlayer.h>
#import "LBAVTopView.h"
#import "LBTILivewCollectionViewCell.h"
#import "LBTILiveConfig.h"
#import <UIButton+LBImageTitleStyle.h>
#import "LBTILiveCollectionTitleView.h"
#import "JYEqualCellSpaceFlowLayout.h"
#import "LBLiveRenderView.h"

#define LBTILiveImage(n)  [UIImage imageNamed:[@"LBTILiveSDK.bundle/" stringByAppendingString:n]]

#define kSCREEN_WIDTH          ([UIScreen mainScreen].bounds.size.width)
#define kSCREEN_HEIGHT         ([UIScreen mainScreen].bounds.size.height)
#define iPhoneX     (kSCREEN_WIDTH == 375.f && kSCREEN_HEIGHT == 812.f)

#define bottomPan (iPhoneX ? 34 : 0)

@interface LBAVBaseView()<ILVLiveAVListener,ILVLiveIMListener,LBAVBaseViewSubWindowDelegate,LBAVBaseViewButtonDelegate,UICollectionViewDelegate,UICollectionViewDataSource>





/** controlView*/
@property(nonatomic,strong)UIView *controlView;

/** controlButtons*/
@property(nonatomic,strong)NSArray<UIButton *> *controlButtons;

/** topView*/
@property(nonatomic,strong)LBAVTopView *topView;

/** firstTitleContainView*/
@property(nonatomic,strong)UIView *firstTitleContainView;

/** secondTitleContainView*/
@property(nonatomic,strong)UIView *secondTitleContainView;

/** MPVolumeView *volumeView;*/
@property(nonatomic,strong)MPVolumeView *volumeView;

//控制的按钮

/** ownSideVideoCount*/
@property(nonatomic,assign)NSInteger ownSideVideoCount;

/** otherSideVideoCount*/
@property(nonatomic,assign)NSInteger otherSideVideoCount;

/** mainScreenUserId*/
@property(nonatomic,copy)NSString *mainScreenUserId;

/** selfId*/
@property(nonatomic,copy)NSString *selfID;

/** collectionView 用于显示默认图和计算宽高*/
@property(nonatomic,strong)UICollectionView *collectionView;


/** renderDic 用于记录曾经绘制过的数据,用于更新背景和名字*/
@property(nonatomic,strong)NSMutableDictionary *renderDic;


@end

@implementation LBAVBaseView


-(instancetype)init
{
    self = [super init];
    if (self) {
        
        
        [self initSubviews];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:67.0/255.0 blue:67.0/255.0 alpha:1];
        _subWindowDelegate = self;
        _buttonDelegate = self;
        
        
        [self initSubviews];
        
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame delegate:(id<LBAVBaseViewDelegate>)delegate
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor colorWithRed:67.0/255.0 green:67.0/255.0 blue:67.0/255.0 alpha:1];
        _subWindowDelegate = self;
        _buttonDelegate = self;
        _delegate = delegate;
        [self initSubviews];
        
    }
    return self;
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    for (UIButton *button in self.controlButtons) {
        [button lb_setButtonImageTitleStyle:ButtonImageTitleStyleTop padding:8];
    }
    
}

-(instancetype)initWithFrame:(CGRect)frame subWindowDelegate:(id<LBAVBaseViewSubWindowDelegate>)subWindowDelegate buttonDelegate:(id<LBAVBaseViewButtonDelegate>)buttonDelegate
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _subWindowDelegate = subWindowDelegate == nil ? self : subWindowDelegate;
        _buttonDelegate = buttonDelegate == nil ? self : subWindowDelegate;
        [self initSubviews];
    }
    return self;
}


-(void)initSubviews
{
    self.selfID = [[[ILiveSDK getInstance] getTIMManager] getLoginUser];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:LBTILiveImage(@"LBAV_background")];
    [self addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    //    [self addSubview:self.collectionView];
    [self addSubview:self.playView];
    
    [self addSubview:self.controlView];
    [self addSubview:self.topView];
    
    [self addSubview:self.firstTitleContainView];
    [self addSubview:self.secondTitleContainView];
    
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.offset(0);
        make.top.offset(0);
        CGFloat height = 120;
        if (self.delegate && [self.delegate respondsToSelector:@selector(heightForTopView)]) {
            height = [self.delegate heightForTopView];
        }
        make.height.mas_equalTo(height);
    }];
    
    [self.firstTitleContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom).offset(20);
        make.leading.trailing.offset(0);
        make.height.equalTo(@20);
        
    }];
    
    [self.secondTitleContainView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        CGFloat videoViewHeight = [UIScreen mainScreen].bounds.size.height - 70 - bottomPan - [self.delegate heightForTopView] - 20;
        make.bottom.equalTo(self.controlView.mas_top).offset(-(videoViewHeight / 2  - 20));
        make.leading.trailing.offset(0);
        make.height.equalTo(@20);
    }];
    
    //    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(self.topView.mas_bottom).offset(18);
    //        make.leading.trailing.offset(0);
    //        make.bottom.equalTo(self.controlView.mas_top);
    //    }];
    
    [self.controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-bottomPan);
        make.leading.trailing.offset(0);
        make.height.equalTo(@70);
    }];
    //    [self.controlView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.leading.trailing.bottom.offset(0);
    //        make.height.equalTo(@50)
    //    }];
    
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        [self rectForSubWindowInAVView:nil identity:nil videoCount:0 videoIndex:0 isOwnSide:YES];
    //    });
}

-(BOOL)isOwnSideWithUserId:(NSString *)userId
{
    BOOL isOwnSide = NO;
    for (LBAVMemberModel *member in self.ownSideMembers) {
        if ([member.userId isEqualToString:userId]) {
            isOwnSide = YES;
            break;
        }
    }
    return isOwnSide;
}

-(LBAVMemberModel *)getMemberModelWithUserId:(NSString *)userId
{
    for (LBAVMemberModel *model in self.ownSideMembers) {
        if ([model.userId isEqualToString:userId]) {
            return model;
        }
    }
    
    for (LBAVMemberModel *model in self.otherSideMembers) {
        if ([model.userId isEqualToString:userId]) {
            return model;
        }
    }
    return nil;
}


-(NSInteger)getMemberIndexWithUserId:(NSString *)userId
{
    for (NSInteger i = 0; i < self.ownSideMembers.count; ++i) {
        LBAVMemberModel *model = self.ownSideMembers[i];
        if ([model.userId isEqualToString:userId]) {
            return i;
            
        }
    }
    
    for (NSInteger i = 0; i < self.otherSideMembers.count; ++i) {
        LBAVMemberModel *model = self.otherSideMembers[i];
        if ([model.userId isEqualToString:userId]) {
            return i;
        }
    }
    
    return -1;
    
}

-(void)startDisplay
{
    
    [[LBTILiveManager shareManager] addAVListener:self];
    [[LBTILiveManager shareManager] addIMListener:self];
    [[LBTILiveManager shareManager] setAVRootView:self.playView];
    
    if (self.role == 0) {
        return;
    }else if (self.role == LBAVRoleHost){
        [[LBTILiveManager shareManager] createRoomWithId:self.roomId];
    }else{
        [[LBTILiveManager shareManager] joinRoomWithId:self.roomId role:self.role];
    }
}


-(void)onUserUpdateInfo:(ILVLiveAVEvent)event users:(NSArray *)users
{
    if (users.count <= 0) {
        return;
    }
    for (NSString *identifier in users) {
        switch (event) {
            case ILVLIVE_AVEVENT_CAMERA_ON:
                if (self.delegate && [self.delegate respondsToSelector:@selector(avView:userEntryRoom:isInData:)]) {
                    [self.delegate avView:self userEntryRoom:identifier isInData:YES];
                }
                [self upCameraVideo:identifier];
                break;
            case ILVLIVE_AVEVENT_CAMERA_OFF:
                if (self.delegate && [self.delegate respondsToSelector:@selector(avView:userQuitRoom:)]) {
                    [self.delegate avView:self userQuitRoom:identifier];
                }
                [self downCameraVideo:identifier];
                
                break;
            default:
                break;
        }
    }
}

- (void)upCameraVideo:(NSString *)identifier{
    //如果之前已经添加过一次renderview，不需要再添加一次了
    //    ILiveFrameDispatcher *dispatch = [[ILiveRoomManager getInstance] getFrameDispatcher];
    
    BOOL isOwnSide;
    if (self.delegate && [self.delegate respondsToSelector:@selector(avView:isOwnSideForUser:)]) {
        isOwnSide = [self.delegate avView:self isOwnSideForUser:identifier];
    }
    
    
    LBAVMemberModel *memberModel = [self getMemberModelWithUserId:identifier];
    
    if (memberModel == nil) {
        //在数组中没有找到,model,无姓名的加入数组
        
        LBAVMemberModel *model = [LBAVMemberModel new];
        model.userId = identifier;
        memberModel = model;
        
        if (isOwnSide) {
            
            [self.ownSideMembers addObject:model];
            
        }else{
            
            [self.otherSideMembers addObject:model];
        }
    }
    
    NSInteger videoIndex = [self getMemberIndexWithUserId:identifier];
    NSLog(@"videoIndex:",@(videoIndex));
    NSInteger videoCount = isOwnSide ? self.ownSideVideoCount : self.otherSideVideoCount;
    NSLog(@"渲染ID:",identifier);
    NSArray *renderViews = [[TILLiveManager getInstance] getAllAVRenderViews];
    for (ILiveRenderView *view in renderViews) {
        if ([view.identifier isEqualToString:identifier]) {
            return;
        }
    }
    
    [self updateNameAndTag];
    
    LBAVRenderModel *renderModel = [[LBAVRenderModel alloc] initWithIdentity:identifier videoCount:videoCount videoIndex:videoIndex isOwnSide:isOwnSide];
    identifier = identifier == nil ? @"" : identifier;
    [self.renderDic setObject:renderModel forKey:identifier];
    
    //判断是否加入了新人
    
    //    NSInteger nowMaxCount = MAX(self.ownSideMembers.count, self.otherSideMembers.count);
    //    if (nowMaxCount != oldMaxCount) {
    //需要更新所有的布局
    [self updateRenderViewLayout];
    //    }
    
    
    
    
    
    
    
    
    CGRect renderRect;
    if (self.subWindowDelegate && [self.subWindowDelegate respondsToSelector:@selector(rectForSubWindowInAVView:identity:videoCount:videoIndex:isOwnSide:)]) {
        renderRect = [self.subWindowDelegate rectForSubWindowInAVView:self identity:identifier videoCount:videoCount videoIndex:videoIndex isOwnSide:isOwnSide];
    }
    
    ILiveRenderView *renderView = [[TILLiveManager getInstance] addAVRenderView:renderRect forIdentifier:identifier srcType:QAVVIDEO_SRC_TYPE_CAMERA];
    renderView.identifier = identifier;
    renderView.memberModel = memberModel;
    renderView.isOwnSide = [NSNumber numberWithBool:isOwnSide];
    renderView.videoIndex = [NSNumber numberWithInteger:videoIndex];
    
    
    
    //    并且向外面请求名字
    //        if (memberModel.userName == nil) {
    //            __weak LBAVBaseView *weakSelf = self;
    //            if (self.delegate && [self.delegate respondsToSelector:@selector(avView:getUserInfoWithUserId:completion:)]) {
    //                [self.delegate avView:self getUserInfoWithUserId:identifier completion:^(LBAVMemberModel *outsideMemberModel) {
    //                    memberModel.userName = outsideMemberModel.userName;
    //                    NSIndexPath *index = [NSIndexPath indexPathForRow:videoIndex inSection:isOwnSide ? 0 : 1];
    //                    [weakSelf.collectionView reloadItemsAtIndexPaths:@[index]];
    //                }];
    //            }
    //        }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(avView:didAddRenderViewForUser:liveRenderView:rect:)]) {
        [self.delegate avView:self didAddRenderViewForUser:identifier liveRenderView:renderView rect:renderRect];
    }
    
    if (isOwnSide) {
        self.ownSideVideoCount++;
    }else{
        self.otherSideVideoCount++;
    }
    
    
    
}

- (void)downCameraVideo:(NSString *)identifier{
    
    
    
    [[TILLiveManager getInstance] removeAVRenderView:identifier srcType:QAVVIDEO_SRC_TYPE_CAMERA];
    if ([self isOwnSideWithUserId:identifier]) {
        self.ownSideVideoCount--;
    }else{
        self.otherSideVideoCount--;
    }
}



#pragma mark - get-set

-(NSMutableDictionary *)renderDic
{
    if (_renderDic == nil) {
        
        _renderDic = [[NSMutableDictionary alloc] init];
        
    }
    return _renderDic;
}

-(NSMutableArray<LBAVMemberModel *> *)ownSideMembers
{
    if (_ownSideMembers == nil) {
        
        _ownSideMembers = [[NSMutableArray alloc] init];
        
    }
    return _ownSideMembers;
}

-(NSMutableArray<LBAVMemberModel *> *)otherSideMembers
{
    if (_otherSideMembers == nil) {
        
        _otherSideMembers = [[NSMutableArray alloc] init];
        
    }
    return _otherSideMembers;
}


-(void)setLb_topView:(UIView *)lb_topView
{
    _lb_topView = lb_topView;
    [self.topView addSubview:self.lb_topView];
    [self.lb_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
}

-(UIView *)playView
{
    if (_playView == nil) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        view.backgroundColor = [UIColor clearColor];
        
        _playView = view;
    }
    return _playView;
}

-(UIView *)controlView
{
    if (_controlView == nil) {
        
        UIView *view = [[UIView alloc] init];
        _controlView = view;
        
        
        
        //设置按钮
        [self layoutButtons];
    }
    return _controlView;
}

-(LBAVTopView *)topView
{
    if (_topView == nil) {
        
        LBAVTopView *view = [[LBAVTopView alloc] init];
        view.backgroundColor = [UIColor clearColor];
        _topView = view;
    }
    return _topView;
}

-(UIView *)firstTitleContainView
{
    if (_firstTitleContainView == nil) {
        
        UIView *view = [[UIView alloc] init];
        _firstTitleContainView = view;
    }
    return _firstTitleContainView;
}

-(UIView *)secondTitleContainView
{
    if (_secondTitleContainView == nil) {
        
        UIView *view = [[UIView alloc] init];
        _secondTitleContainView = view;
    }
    return _secondTitleContainView;
}

-(void)setFirstTitleView:(UIView *)firstTitleView
{
    _firstTitleView = firstTitleView;
    [self.firstTitleContainView addSubview:_firstTitleView];
    [self.firstTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
}

-(void)setSecondTitleView:(UIView *)secondTitleView
{
    _secondTitleView = secondTitleView;
    [self.secondTitleContainView addSubview:_secondTitleView];
    [self.secondTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
}

-(void)layoutButtons
{
    
    if (self.buttonDelegate && [self.buttonDelegate respondsToSelector:@selector(listOfButton)]) {
        NSArray *array = [self.buttonDelegate listOfButton];
        UIButton *button;
        if (self.delegate && [self.delegate customButton]) {
            button = [self.delegate customButton];
        }
        NSMutableArray *buttons = [[NSMutableArray alloc] initWithArray:array];
        if (button) {
            [buttons insertObject:button atIndex:0];
        }
        
        self.controlButtons = array;
        
        for (NSInteger i = 0; i < buttons.count; ++i) {
            
            
            UIButton *button = buttons[i];
            //            button.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 5 * i, 0, [UIScreen mainScreen].bounds.size.width / 5, 50);
            [self.controlView addSubview:button];
        }
        
        
        
        [array mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:100 tailSpacing:0];
        [array mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.offset(0);
            make.top.bottom.offset(0);
        }];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.offset(0);
            make.top.bottom.offset(0);
            make.width.equalTo(@90);
        }];
        
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self.controlView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@0.5);
            make.centerY.offset(0);
            make.height.equalTo(@40);
            make.trailing.equalTo(button).offset(1);
        }];
    }
}

#pragma mark - subWindow

-(CGRect)rectForSubWindowInAVView:(LBAVBaseView *)avView identity:(NSString *)identity videoCount:(NSInteger)videoCount videoIndex:(NSInteger)videoIndex isOwnSide:(BOOL)isOwnSide
{
    
    
    
    //    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:videoIndex inSection:isOwnSide ? 0 : 1];
    //
    //    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    //    CGRect rect = [cell.superview convertRect:cell.frame toView:self];
    //    //以为cell是高度+了20
    //    CGRect videoRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height - 20);
    
    //    return videoRect;
    
    NSInteger maxItemCount = MAX(self.ownSideMembers.count, self.otherSideMembers.count);
    NSInteger sideCount = isOwnSide ? self.ownSideMembers.count : self.otherSideMembers.count;
    
    
    CGFloat itemWidth;
    CGFloat itemHeight;
    CGFloat pan;
    CGFloat topPan;
    CGFloat titleViewToTopPan = 20;
    CGFloat x;
    CGFloat y;
    CGFloat leftPan = 20;
    CGFloat sectionTitleHeight = 20;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat controlViewHeight = 70 + bottomPan;
    CGFloat videoViewHeight = screenHeight - controlViewHeight - [self.delegate heightForTopView] - titleViewToTopPan;
    if (maxItemCount <= 2) {
        
        pan = 20;
        topPan = 20;
        CGFloat scale = (148.0 / 197.0);
        
        CGFloat sectionHeight = (videoViewHeight / 2) - sectionTitleHeight;
        itemHeight = sectionHeight - topPan * 2;
        itemWidth = sectionHeight * scale;
        if (screenWidth < itemWidth * 2 + leftPan * 2 + pan) {
            itemWidth = (screenWidth - leftPan * 2 - pan) / 2;
        }
        if (isOwnSide) {
            y = [self.delegate heightForTopView] + sectionTitleHeight + topPan + titleViewToTopPan;
        }else{
            y = [self.delegate heightForTopView] + sectionTitleHeight * 2 + sectionHeight + topPan + titleViewToTopPan;
        }
        
        if (sideCount == 1) {
            x = ([UIScreen mainScreen].bounds.size.width - itemWidth) / 2;
        }else{
            if (videoIndex == 0) {
                x = ([UIScreen mainScreen].bounds.size.width / 2 - itemWidth) - pan / 2;
            }else{
                x = [UIScreen mainScreen].bounds.size.width / 2 + pan / 2;
            }
        }
        
    }else{
        
        pan = 10;
        CGFloat scale = 78.0 / 128.0;
        itemWidth = (screenWidth - leftPan * 2 - (maxItemCount - 1) * pan) / maxItemCount;
        itemHeight = itemWidth / scale;
        CGFloat sectionHeight = (videoViewHeight / 2) - sectionTitleHeight;
        if (isOwnSide) {
            y = [self.delegate heightForTopView] + sectionTitleHeight + (sectionHeight - itemHeight)/2 + titleViewToTopPan;
        }else{
            y = [self.delegate heightForTopView] + sectionHeight + sectionTitleHeight * 2 + (sectionHeight - itemHeight)/2 + titleViewToTopPan;
        }
        
        if (sideCount == 1) {
            x = ([UIScreen mainScreen].bounds.size.width - itemWidth) / 2;
        }else if(sideCount == 2){
            if (videoIndex == 0) {
                x = ([UIScreen mainScreen].bounds.size.width / 2 - itemWidth) - pan / 2;
            }else{
                x = [UIScreen mainScreen].bounds.size.width / 2 + pan / 2;
            }
        }else{
            x = 20 + itemWidth * videoIndex + videoIndex * pan;
        }
        
        
        
    }
    
    CGRect rect = CGRectMake(x, y, itemWidth, itemHeight);
    
    NSLog(@"%@",NSStringFromCGRect(rect));
    
    return rect;
    
    //
    //    CGFloat pan = 15;
    //
    //    CGFloat itemWidth = (([UIScreen mainScreen].bounds.size.width - ((maxItemCount + 1) * pan + 10)) / maxItemCount);
    //
    //    CGFloat itemHeight = (itemWidth / lb_videoScale);
    //
    //    return CGRectZero;
    
    
}

-(void)updateRenderViewLayout
{
    NSArray *renderViews = [[TILLiveManager getInstance] getAllAVRenderViews];
    
    for (ILiveRenderView *rendView in renderViews) {
        NSInteger videoCount = rendView.isOwnSide ? self.ownSideVideoCount : self.otherSideVideoCount;
        CGRect rect = [self rectForSubWindowInAVView:self identity:rendView.identifier videoCount:videoCount videoIndex:[rendView.videoIndex integerValue] isOwnSide:[rendView.isOwnSide boolValue]];
        [[TILLiveManager getInstance] modifyAVRenderView:rect forIdentifier:rendView.identifier srcType:QAVVIDEO_SRC_TYPE_CAMERA];
        
    }
    
    
}

-(void)updateNameAndTag
{
    for (NSString *key in self.renderDic.allKeys) {
        LBAVRenderModel *renderModel = [self.renderDic objectForKey:key];
        NSLog(@"identity:%@ videoCount:%ld videoIndex:%ld isOwnSide:%ld",renderModel.identity,renderModel.videoCount,renderModel.videoIndex,renderModel.isOwnSide);
        CGRect rect = [self rectForSubWindowInAVView:self identity:renderModel.identity videoCount:renderModel.videoCount videoIndex:renderModel.videoIndex isOwnSide:renderModel.isOwnSide];
        NSLog(@"rect:%@",NSStringFromCGRect(rect));
        if (self.delegate && [self.delegate respondsToSelector:@selector(avView:didAddRenderViewForUser:liveRenderView:rect:)]) {
            [self.delegate avView:self didAddRenderViewForUser:renderModel.identity liveRenderView:nil rect:rect];
        }
    }
}


#pragma mark - button

-(UIButton *)defaultCameraButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setImage:LBTILiveImage(@"LBAV_camera") forState:UIControlStateNormal];
    [button setImage:LBTILiveImage(@"LBAV_camera_selected") forState:UIControlStateSelected];
    [button setTitle:@"摄像头" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(cameraAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

-(UIButton *)defaultVoiceButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setImage:LBTILiveImage(@"LBAV_speaker") forState:UIControlStateNormal];
    [button setImage:LBTILiveImage(@"LBAV_speaker_selected") forState:UIControlStateSelected];
    [button setTitle:@"免提" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(speakerAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

-(UIButton *)defaultScreenButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setTitle:@"放大缩小" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(screenAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
    
}

-(UIButton *)defaultSwitchButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setImage:LBTILiveImage(@"LBAV_switch") forState:UIControlStateNormal];
    [button setImage:LBTILiveImage(@"LBAV_switch_selected") forState:UIControlStateSelected];
    [button setTitle:@"反转" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
    
}

-(UIButton *)defaultMicButton
{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setImage:LBTILiveImage(@"LBAV_silent") forState:UIControlStateNormal];
    [button setImage:LBTILiveImage(@"LBAV_silent_selected") forState:UIControlStateSelected];
    [button setTitle:@"麦克风" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(micAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

-(UIButton *)defaultTextButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button setTitle:@"发消息" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(sendTextAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

-(void)sendTextAction:(id)sender
{
    
}

//扬声器
-(void)speakerAction:(UIButton *)sender
{
    if (sender.isSelected) {
        [[ILiveRoomManager getInstance] setAudioMode:QAVOUTPUTMODE_SPEAKER];
    }else{
        [[ILiveRoomManager getInstance] setAudioMode:QAVOUTPUTMODE_EARPHONE];
    }
    sender.selected = !sender.selected;
}

-(void)cameraAction:(UIButton *)sender
{
    
    if (sender.isSelected) {
        [[LBTILiveManager shareManager] openCamera];
    }else{
        [[LBTILiveManager shareManager] closeCamera];
    }
    sender.selected = !sender.selected;
}

-(void)micAction:(UIButton *)sender
{
    if (sender.isSelected) {
        [[LBTILiveManager shareManager] onOpenMic];
    }else{
        [[LBTILiveManager shareManager] closeMic];
    }
    sender.selected = !sender.selected;
}



-(void)switchAction:(UIButton *)sender
{
    [[LBTILiveManager shareManager] onSwitchCamera];
}

-(void)screenAction:(UIButton *)sender
{
    NSString *selfId = [[[ILiveSDK getInstance] getTIMManager] getLoginUser];
    if (sender.isSelected) {
        [[TILLiveManager getInstance] modifyAVRenderView:CGRectMake(0, 0, self.frame.size.width, 400) forIdentifier:selfId srcType:QAVVIDEO_SRC_TYPE_CAMERA];
        self.playView.frame = CGRectMake(0, 0, self.frame.size.width, 400);
    }else{
        NSLog(@"自己的ID%@",selfId);
        [[TILLiveManager getInstance] modifyAVRenderView:CGRectMake(0, 0, self.frame.size.width, [UIScreen mainScreen].bounds.size.height) forIdentifier:selfId srcType:QAVVIDEO_SRC_TYPE_CAMERA];
        self.playView.frame = CGRectMake(0, 0, self.frame.size.width, [UIScreen mainScreen].bounds.size.height);
    }
    sender.selected = !sender.selected;
    
}

-(void)switchMainScreen:(UITapGestureRecognizer *)sender
{
    ILiveRenderView *view = sender.view;
    ILiveRenderView *mainView = [[TILLiveManager getInstance] getAVRenderView:self.mainScreenUserId srcType:QAVVIDEO_SRC_TYPE_CAMERA];
    NSString *userId = view.identifier;
    NSLog(@"大屏identity%@",self.mainScreenUserId);
    NSLog(@"小屏identity%@",view.identifier);
    
    if (!view || !mainView) {
        return;
    }
    
    [[TILLiveManager getInstance] switchAVRenderView:self.mainScreenUserId srcType:QAVVIDEO_SRC_TYPE_CAMERA with:userId anotherSrcType:QAVVIDEO_SRC_TYPE_CAMERA];
    
    mainView.identifier = userId;
    view.identifier = self.mainScreenUserId;
    
    LBAVMemberModel *tempMember = [[LBAVMemberModel alloc] init];
    tempMember.userId = mainView.memberModel.userId;
    tempMember.userName = mainView.memberModel.userName;
    
    mainView.memberModel = view.memberModel;
    view.memberModel = tempMember;
    
    
    
    
    [self updateRenderViewUIIsSwitch:YES];
}

//用于更新主屏幕UI,小窗名字,还有小窗的手势,因为在切换的时候需要处理,进入的时候也需要处理,这里统一重新处理设置
-(void)updateRenderViewUIIsSwitch:(BOOL)isSwitch
{
    
    //先设置主画面ID,
    //设置手势的生效或者时效
    //设置标签
    NSArray *renderviews = [[TILLiveManager getInstance] getAllAVRenderViews];
    for (ILiveRenderView *view in renderviews) {
        if (view.bounds.size.width == self.frame.size.width) {
            self.mainScreenUserId = view.identifier;
            if (!isSwitch) {
                [[TILLiveManager getInstance] sendAVRenderViewToBack:view.identifier srcType:QAVVIDEO_SRC_TYPE_CAMERA];
            }
            if (view.gestureRecognizers.count > 0 ) {
                UITapGestureRecognizer *tap = [view.gestureRecognizers firstObject];
                tap.enabled = NO;
            }
            [view updateNameWithString:nil];
            
        }else{
            if (view.gestureRecognizers.count > 0 ) {
                UITapGestureRecognizer *tap = [view.gestureRecognizers firstObject];
                tap.enabled = YES;
            }
            [view updateNameWithString:view.memberModel.userName];
        }
    }
    
    
}

-(void)reloadCollectionView
{
    [self.collectionView reloadData];
}

-(UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);
        flowLayout.minimumLineSpacing = 100;
        flowLayout.minimumInteritemSpacing = 15;
        
        flowLayout.headerReferenceSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 30);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[LBTILivewCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([LBTILivewCollectionViewCell class])];
        [_collectionView registerClass:[LBTILiveCollectionTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LBTILiveCollectionTitleView class])];
    }
    return _collectionView;
}




#pragma mark - delegate

-(NSArray<UIButton *> *)listOfButton
{
    //    UIButton *textButton = [self defaultTextButton];
    
    UIButton *micButton = [self defaultMicButton];
    UIButton *voiceButton = [self defaultVoiceButton];
    UIButton *cameraButton = [self defaultCameraButton];
    UIButton *switchButton = [self defaultSwitchButton];
    
    NSArray *array = @[voiceButton,micButton,cameraButton,switchButton];
    
    
    return array;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LBTILivewCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LBTILivewCollectionViewCell class]) forIndexPath:indexPath];
    LBAVMemberModel *memberModel;
    if (indexPath.section == 0) {
        memberModel = self.ownSideMembers[indexPath.row];
        
    }else{
        
        memberModel = self.otherSideMembers[indexPath.row];
    }
    [cell configCellWithData:memberModel atIndexPath:indexPath totalListNumber:(indexPath.section == 0 ? self.ownSideMembers.count : self.otherSideMembers.count)];
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        LBTILiveCollectionTitleView *titleView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LBTILiveCollectionTitleView class]) forIndexPath:indexPath];
        NSString *title;
        if (self.delegate && [self.delegate respondsToSelector:@selector(avView:titleForSection:)]) {
            title = [self.delegate avView:self titleForSection:indexPath.section];
        }
        titleView.titleLabel.text = title;
        return titleView;
    }
    
    return nil;
    
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger maxItemCount = MAX(self.ownSideMembers.count, self.otherSideMembers.count);
    
    if (maxItemCount <= 2) {
        
        //
        CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
        CGFloat collectionViewHeight = screenHeight - 70 - [self.delegate heightForTopView];
        CGFloat sectionHeight = (collectionViewHeight / 2) - 20;
        return CGSizeMake(sectionHeight * (148 / 197), sectionHeight);
    }
    
    CGFloat pan = 15;
    
    CGFloat itemWidth = (([UIScreen mainScreen].bounds.size.width - ((maxItemCount + 1) * pan + 10)) / maxItemCount);
    
    CGFloat itemHeight = (itemWidth / lb_videoScale);
    
    return CGSizeMake(itemWidth, itemHeight + 20);
}



-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return section == 0 ? self.ownSideMembers.count : self.otherSideMembers.count;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end











@implementation LBAVMemberModel

@end


@implementation LBAVRenderModel

-(instancetype)initWithIdentity:(NSString *)identity videoCount:(NSInteger)videoCount videoIndex:(NSInteger)videoIndex isOwnSide:(BOOL)isOwnSide
{
    self = [super init];
    if (self) {
        
        _identity = identity;
        _videoCount = videoCount;
        _videoIndex = videoIndex;
        _isOwnSide = isOwnSide;
        
    }
    return self;
}

@end








